package errcode

import (
	"fmt"
	"net/http"
)

var (
	Success                   = NewError(0, "success")
	ServerError               = NewError(10000, "server error")
	InvalidParams             = NewError(10001, "params error")
	NotFound                  = NewError(10002, "not found")
	UnauthorizedAuthNotExist  = NewError(10003, "auth failed")
	UnauthorizedTokenError    = NewError(10004, "token not found")
	UnauthorizedTokenTimeout  = NewError(10005, "token timeout")
	UnauthorizedTokenGenerate = NewError(10006, "token create failed")
	TooManyRequests           = NewError(10007, "too many requests")
	ErrUploadFileFailed       = NewError(20001, "upload file failed")
)

type Error struct {
	code    int      `json:"code"`
	msg     string   `json:"msg"`
	details []string `json:"details"`
}

var codes = map[int]string{}

func NewError(code int, msg string) *Error {
	if _, ok := codes[code]; ok {
		panic(fmt.Sprintf("error code %d is exist", code))
	}
	codes[code] = msg
	return &Error{code: code, msg: msg}
}

func (e *Error) Code() int {
	return e.code
}

func (e *Error) Msg() string {
	return e.msg
}

func (e *Error) Error() string {
	return fmt.Sprintf("errcode: %d, errmsg: %s", e.Code(), e.Msg())
}

func (e *Error) Msgf(args []interface{}) string {
	return fmt.Sprintf(e.msg, args)
}

func (e *Error) Details() []string {
	return e.details
}

func (e *Error) WithDetails(details ...string) *Error {
	e.details = make([]string, 0, len(details))

	for _, d := range details {
		e.details = append(e.details, d)
	}

	return e
}

func (e *Error) StatusCode() int {
	switch e.Code() {
	case Success.Code():
		return http.StatusOK
	case ServerError.Code():
		return http.StatusInternalServerError
	case InvalidParams.Code(), UnauthorizedAuthNotExist.Code(), UnauthorizedTokenError.Code(), UnauthorizedTokenGenerate.Code():
		return http.StatusBadRequest
	case UnauthorizedTokenTimeout.Code():
		return http.StatusUnauthorized
	case TooManyRequests.Code():
		return http.StatusTooManyRequests
	}

	return http.StatusInternalServerError
}
